{% extends 'common_project_tpl.html' %}
{% load static %}
{% block css %}
    <link rel="stylesheet" href="{% static 'plugins/editor-md/css/editormd.min.css' %}">
    <link rel="stylesheet" href="{% static 'plugins/editor-md/css/editormd.preview.min.css' %}">
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-datepicker/css/bootstrap-datepicker.min.css' %}">
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-select/css/bootstrap-select.min.css' %}">
    <style>
        .panel-default .panel-heading {
        {# 弹性盒子，指定主轴方向为行对齐，对齐方式，两端对齐#} display: flex;
            flex-direction: row;
            justify-content: space-between;
        }

        .too-long {
            text-overflow: ellipsis; /* text-overflow:ellipsis的意思就是：显示省略符号来代表被修剪的文本 */
            overflow: hidden; /* overflow:hidden意思是：内容会被修剪，并且其余内容是不可见的。*/
            white-space: nowrap; /* white-space:nowrap意思是：文本不会换行，文本会在在同一行上继续，直到遇到 <br> 标签为止。*/
        }

        .issues-list .number {
            width: 100px;
            text-align: right;
        }

        .issues-list .number a {
            font-weight: 500;
            padding: 0 10px;
        }

        .page-header .tags {
            padding: 10px 0;
        }

        .page-header .tags span {
            margin-right: 20px;
            display: inline-block;
            font-size: 12px;
            vertical-align: top; /* overflow:hidden会改变inline-block对齐基线，重新指定即可*/
        }

        .issues-list .issue .tags .type {
            color: white;
            padding: 1px 5px;
            border-radius: 5px;
            background-color: #dddddd;
        }

        .editormd-fullscreen {
            z-index: 1001;
        }

        .error-msg {
            color: red;
            position: static;
        }

        .comment-area .item {
            margin-top: 20px;
        }

        .comment-area .left-avatar {
            float: left;
            margin-right: 10px;
            display: inline-block;
            width: 30px;
            height: 30px;
            background-color: #304659;
            color: white;
            text-align: center;
            line-height: 30px;
            border-radius: 50%;
        }

        .comment-area .right-info {
            padding-left: 35px;
        }

        .comment-area .right-info .desc .msg {
            display: inline-block;
            padding-right: 20px;
            color: #8c8c8c;
        }

        .comment-area .child {
            padding-left: 55px;
        }

        .comment-area .error-msg {
            color: red;
        }

        .comment-area .reply-user {
            display: inline-block;
            background-color: #ddd;
            color: black;
            padding: 6px 8px;
            margin-left: 20px;
            border-radius: 8px;
            cursor: pointer;
        }

        .flex {
            display: flex;
        }

        #reply-panel {
            flex: 1;
        }

        pre {
            white-space: pre-wrap;
            word-wrap: break-word;
        }

    </style>
{% endblock %}
{% block content %}
    <div class="container-fluid clearfix flex" style="padding: 20px 0;">
        <div class="col-sm-7" id="detail-panel">
            <div class="panel panel-default" style="height: 100%">
                <div class="panel-heading">
                    <div>
                        <i class="fa fa-edit" aria-hidden="true"></i> 问题详情
                    </div>
                    <div>
                        <a href="#" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#editIssue">编辑</a>
                    </div>
                </div>
                <div class="panel-body filter-area">
                    <div class="page-header">
                        <h3 class="text-primary">
                            <i class="fa fa-bookmark" aria-hidden="true"></i> {{ obj.subject }}
                            {#                            <small>Subtext for header</small>#}
                        </h3>
                        <div class="tags">
                            <span class='label label-info type'>{{ obj.issues_type.title }}</span>

                            <span>
                                <i class="fa fa-refresh" aria-hidden="true"></i>
                                {{ obj.get_status_display }}
                            </span>

                            <span>
                                <i class="fa fa-hand-o-right" aria-hidden="true"></i>
                                {% if obj.assign %}
                                    {{ obj.assign.realname }}
                                {% else %}
                                    未指派
                                {% endif %}
                            </span>

                            <span>
                                <i class="fa fa-user-o" aria-hidden="true"></i>
                                {{ obj.creator.realname }}
                            </span>

                            <span><i class="fa fa-calendar" aria-hidden="true"></i>
                                {% if obj.end_date %}
                                    {{ obj.end_date }} 截止
                                {% else %}
                                    无限期
                                {% endif %}
                            </span>

                            <span><i class="fa fa-clock-o" aria-hidden="true"></i>
                                {{ obj.latest_update_datetime }} 更新
                            </span>

                            <span class="too-long" style="width: 200px;">
                                {% if obj.attention.all %}
                                    <i class="fa fa-eye" aria-hidden="true"></i>
                                {% endif %}

                                <span class="tt">
                                    {% for item in obj.attention.all %}
                                        {{ item.realname }}
                                    {% endfor %}
                                </span>
                            </span>
                        </div>
                    </div>
                    <div id="previewMarkdown">
                        {{ form.desc }}
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-5" id="reply-panel">
            <div class="panel panel-default" style="height: 100%">
                <div class="panel-heading">
                    <div>
                        <i class="fa fa-search" aria-hidden="true"></i> 操作记录
                    </div>
                </div>
                <div class="panel-body comment-area">
                    <div class="comment-list pre-scrollable" style="min-height: 20px">

                    </div>

                    <div id="recordTemplate" class="hide">
                        <div class="item clearfix">
                            <div class="left-avatar">W</div>
                            <div class="right-info">
                                <pre>这是评论的内容</pre>
                                <div class="desc">
                                    <div class="msg">
                                        <i class="fa fa-bullhorn" aria-hidden="true"></i>
                                        <span class="type">评论</span>
                                    </div>
                                    <div class="msg">
                                        <i class="fa fa-user-o" aria-hidden="true"></i>
                                        <span class="user">bill</span>
                                    </div>
                                    <div class="msg">
                                        <i class="fa fa-clock-o" aria-hidden="true"></i>
                                        <span class="date">2023年11月3日19:17:55</span>
                                    </div>

                                    <a href="#commentText" class="reply">
                                        <i class="fa fa-commenting-o" aria-hidden="true"></i> 回复
                                    </a>
                                </div>
                            </div>
                            <div class="child">


                            </div>
                        </div>
                    </div>
                    <hr/>
                    <div class="comment-text" id="commentText" style="margin-top: 20px;">

                        <div class="form-group">
                            <textarea id="content" rows="6" class="form-control"
                                      placeholder="请输入要回复的内容" style="resize: none"></textarea>
                            <span class="error-msg"></span>
                        </div>

                        <input class="btn btn-primary" type="button" id="btnSubmit" value="提 交">
                        <div class="reply-user hide" id="replyUser">
                            回复 <span></span>
                            <i class="fa fa-times-circle" aria-hidden="true" style="color: #9d9d9d;"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- Modal -->
    <div class="modal fade" id="editIssue" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">修改问题</h4>
                </div>
                <div class="modal-body" style="padding-right: 40px;">
                    <form id="issue-form" class="form-horizontal">
                        {% csrf_token %}
                        <div class="form-group">
                            <label for="{{ form.issues_type.id_for_label }}"
                                   class="col-md-2 control-label">{{ form.issues_type.label }}</label>
                            <div class="col-md-10">
                                <div>
                                    <div>
                                        {{ form.issues_type }}
                                        <div class="error-msg"></div>
                                    </div>
                                </div>
                                <div class="error-msg"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="{{ form.subject.id_for_label }}"
                                   class="col-md-2 control-label">{{ form.subject.label }}</label>
                            <div class="col-md-10">
                                <div>
                                    <div>
                                        {{ form.subject }}
                                    </div>
                                    <div class="error-msg"></div>
                                </div>
                                <div class="error-msg"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="{{ form.module.id_for_label }}"
                                   class="col-md-2 control-label">{{ form.module.label }}</label>
                            <div class="col-md-10">
                                <div>
                                    <div>
                                        {{ form.module }}
                                    </div>
                                    <div class="error-msg"></div>
                                </div>
                                <div class="error-msg"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="{{ form.desc.id_for_label }}"
                                   class="col-md-2 control-label">{{ form.desc.label }}</label>
                            <div class="col-md-10">
                                <div>
                                    <div id="editor">
                                        {{ form.desc }}
                                    </div>

                                    <div class="error-msg"></div>
                                </div>
                                <div class="error-msg"></div>
                            </div>
                        </div>

                        <div class="form-group clearfix">

                            <div class="col-md-6 pd-0">
                                <label for="{{ form.status.id_for_label }}"
                                       class="col-md-4 control-label">{{ form.status.label }}</label>
                                <div class="col-md-8 clearfix">
                                    <div>
                                        {{ form.status }}
                                    </div>
                                    <div class="error-msg"></div>

                                </div>
                            </div>
                            <div class="col-md-6 pd-0">
                                <label for=" {{ form.priority.id_for_label }}"
                                       class="col-md-4 control-label">{{ form.priority.label }}</label>
                                <div class="col-md-8">
                                    <div>
                                        {{ form.priority }}
                                    </div>
                                    <div class="error-msg"></div>

                                </div>
                            </div>
                        </div>

                        <div class="form-group clearfix">
                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">指派给</label>
                                <div class="col-md-8">
                                    {{ form.assign }}
                                    <div class="error-msg"></div>
                                </div>
                            </div>

                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">关注者</label>
                                <div class="col-md-8">

                                    {{ form.attention }}

                                    <div class="error-msg"></div>
                                </div>
                            </div>
                        </div>

                        <div class="form-group clearfix">
                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">开始时间</label>
                                <div class="col-md-8">

                                    <div class="input-group">
                                        <span class="input-group-addon" id="sizing-addon2">
                                            <i class="fa fa-calendar" aria-hidden="true"></i>
                                        </span>
                                        {{ form.start_date }}
                                    </div>
                                    <span class="error-msg"></span>

                                </div>
                            </div>

                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">截止时间</label>
                                <div class="col-md-8">

                                    <div class="input-group">
                                        <span class="input-group-addon" id="sizing-addon2">
                                            <i class="fa fa-calendar" aria-hidden="true"></i>
                                        </span>
                                        {{ form.end_date }}
                                    </div>
                                    <span class="error-msg"></span>
                                </div>
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">模式</label>
                                <div class="col-md-8">
                                    <div>
                                        {{ form.mode }}
                                    </div>
                                    <div class="error-msg"></div>
                                </div>
                            </div>

                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label"> 父问题</label>
                                <div class="col-md-8">

                                    {{ form.parent }}

                                    <div class="error-msg"></div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消
                    </button>
                    <button id="edit_issue" type="button" class="btn btn-primary">保存</button>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block js %}
    <script src="{% static 'plugins/editor-md/editormd.min.js' %}"></script>
    <script src="{% static 'plugins/editor-md/lib/marked.min.js' %}"></script>
    <script src="{% static 'plugins/editor-md/lib/prettify.min.js' %}"></script>
    <script src="{% static 'plugins/editor-md/lib/raphael.min.js' %}"></script>
    <script src="{% static 'plugins/editor-md/lib/underscore.min.js' %}"></script>
    <script src="{% static 'plugins/editor-md/lib/sequence-diagram.min.js' %}"></script>
    <script src="{% static 'plugins/editor-md/lib/flowchart.min.js' %}"></script>
    <script src="{% static 'plugins/editor-md/lib/jquery.flowchart.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-select/js/bootstrap-select.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-select/js/i18n/defaults-zh_CN.min.js' %}"></script>
    <script>
        let changes_list = {};
        let EDITOR;
        $(function () {
            initModal();
            initDatePicker();
            editIssue();
            initPreivewMarkdown();
            initPage();
            getReply();
            bindReply();
            bindCancelReplyUser();
            bindReplySubmit();
            initHeight();
            bindChangeIssue();
        })

        function initPage() {
            let el = $('.too-long');
            if (el.children('.tt').text().match(/\S+/g)){
                el.attr('title', el.children('.tt').text().match(/\S+/g).join(' '));
            }
            let max_height = $(window).height();
            $('.comment-list').css('max-height', (0.6 * max_height) + 'px');
        }

        function initHeight() {
            $(window).resize(function () {
                let max_height = $(window).height();
                $('.comment-list').css('max-height', (0.6 * max_height) + 'px');
            })
        }

        function initPreivewMarkdown() {
            editormd.markdownToHTML("previewMarkdown", {
                htmlDecode: "style,script,iframe"
                // 过滤，将其中这些内容过滤掉,出于安全性考虑，本质上是让其中的内容以纯字符串显示
            });
        }

        function initModal() {
            $('#editIssue').on('shown.bs.modal', function (event) { // 当模态框显示时，会自动触发此函数
                initEditorMd();
            })
        }

        function initEditorMd() {
            EDITOR = editormd('editor', {
                placeholder: "请输入问题描述",
                height: 300,
                path: "{% static 'plugins/editor-md/lib/' %}",
                // 上传图片的开关
                imageUpload: true,
                // 上传图片允许格式
                imageFormats: ["jpg", 'jpeg', 'png', 'gif'],
                // 上传图片的接口，会自动向该接口发送post请求，已经在组件中封装好了
                imageUploadURL: "{% url 'main:api_wiki_upload' project=pro_id %}" + '?project=' +{{ pro_id }},
                flowChart: true,
                emoji: true,
                table: true,
                /*
                onload: function () {
                    this.previewing();
                }*/
            })
        }

        function initDatePicker() {

            $('#id_start_date,#id_end_date').datepicker({
                format: 'yyyy-mm-dd', // 显示的数据格式
                {#startDate: '0', // 表示从今天开始选择#}
                language: "zh-CN",
                autoclose: true
            });
        }

        function editIssue() {
            $("#edit_issue").click(function () {
                $('.error-msg').empty();
                let data = changes_list;
                /*
                let data = {};
                let attention = [];
                $.each($('#issue-form').serializeArray(), function () {
                    if (this.name === "attention") {
                        attention.push(this.value);
                    } else {
                        data[this.name] = this.value;
                    }
                });
                data.attention = attention*/
                data.project ={{ pro_id }};
                data.desc = EDITOR.getValue();
                $.ajax({
                    url: "{% url 'main:issue-detail' issue_id %}",
                    data: JSON.stringify(data),
                    dataType: 'json',
                    type: 'put',
                    contentType: 'application/json',
                    headers: {
                        'X-CSRFTOKEN': $("[name='csrfmiddlewaretoken']").val() // 传入csrftoken
                    },
                    success: function (res) {
                        if (res.ret === 0) {
                            changes_list = {}
                            location.reload();
                        } else {
                            $.each(res.errors, function (key, value) {
                                $("#id_" + key).parent().next(".error-msg").text(value[0]);
                            })
                        }
                    }

                })
            })

        }

        function getReply() {
            $.ajax({
                url: "{% url 'main:reply-list' %}",
                data: {
                    project:{{ pro_id }},
                    issues:{{ issue_id }}
                },
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    console.log(res);
                    if (res.ret === 0) {
                        $.each(res.data, function (index, item) {
                            refreshReply(item);
                        })
                    }
                }
            })
        }

        function refreshReply(item) {
            let tpl = $("#recordTemplate").children("div").clone();
            tpl.find('.left-avatar').text(item.creator_name[0].toUpperCase());
            tpl.find('pre').text(item.content);
            if (item.reply_type === '修改记录') {
                tpl.find('pre').css('background-color', 'pink')
            }
            tpl.find('.type').text(item.reply_type);
            tpl.find('.user').text(item.creator_name);
            tpl.find('.date').text(item.create_datetime);
            tpl.find('.child').attr('id', 'reply' + item.id);
            tpl.find('.child').attr('username', item.creator_name);
            if (item.reply) {
                $('#reply' + item.reply).append(tpl);
            } else {
                $(".comment-list").append(tpl);
            }

        }

        function bindReply() {
            $(".comment-area").on("click", '.reply', function () {
                let info_el = $(this).parent().parent().next('.child');
                let id = info_el.attr('id').match(/\d+/)[0]
                $('#replyUser').removeClass('hide').attr('parent-id', id).children('span').text(info_el.attr("username"))
            })
        }

        function bindCancelReplyUser() {

            $('#replyUser').click(function () {
                $(this).addClass('hide').removeAttr('parent-id').children('span').text("");
            })
        }

        function bindReplySubmit() {
            $('#btnSubmit').click(function () {
                $('.error-msg').empty();
                let data = {
                    project:{{ pro_id }},
                    issues:{{ issue_id }},
                    content: $('#content').val(),
                    creator:{{ request.user.id }},
                    reply: $('#replyUser').attr('parent-id'),
                    reply_type: 2
                };

                $.ajax({
                    url: "{% url 'main:reply-list' %}",
                    type: 'post',
                    data: data,
                    dataType: 'json',
                    headers: {
                        'X-CSRFTOKEN': $("[name='csrfmiddlewaretoken']").val() // 传入csrftoken
                    },
                    success: function (res) {
                        if (res.ret === 0) {
                            refreshReply(res.data);
                            $('#replyUser').addClass('hide').removeAttr('parent-id').children('span').text("");
                            $('#content').val('');
                        } else {
                            $.each(res.errors, function () {
                                console.log(this[0])
                                $('#content').next('span').text(this[0])
                            })
                        }
                    }
                })
            })
        }

        function bindChangeIssue() {
            $("#issue-form").find('.form-control').change(function () {
                changes_list[$(this).attr('name')] = $(this).val();
                console.log(changes_list)
            })
        }
    </script>
{% endblock %}